Skip to content

[http_server] Cache parameter child pointer for O(1) lookup fallback - #4

Closed
cong1920 wants to merge 1 commit into
simplify_drt_nodefrom
perf/cache-param-child
Closed

[http_server] Cache parameter child pointer for O(1) lookup fallback#4
cong1920 wants to merge 1 commit into
simplify_drt_nodefrom
perf/cache-param-child

Conversation

@cong1920

Copy link
Copy Markdown
Owner

Summary

Cache the {{param}} child pointer during route registration ( ind_or_create) so that ind() can fall back to it in O(1) instead of doing a linear scan of all children.

Problem

In ind(), when a static child lookup misses, the code did a linear scan of ALL children to find a {{param}} child:

\\cpp
for (const auto& kv : children_) {
if (name.size() > 4 and name[0] == '{' and name[1] == '{' ...)
return kv.second->find(r, c);
}
\\

This is O(n) per tree level for every parameterized route lookup.

Fix

Added a cached pointer set during \ ind_or_create():

\\cpp
drt_node* param_child_ = nullptr;
\\

Now \ ind()\ falls back in O(1):

\\cpp
if (param_child_)
return param_child_->find(r, c);
return end();
\\

Benchmark Results

Environment: WSL2 Ubuntu, g++ -O2 -std=c++20, 25 iterations

Metric Before After Change
insert 313.3 ns/op 299.2 ns/op -4.5%
lookup hit 80.7 ns/op 72.7 ns/op -9.9%
lookup miss 45.0 ns/op 36.6 ns/op -18.7%

vs master branch

Metric master This PR Change
insert 268.2 ns/op 299.2 ns/op +11.6% (structural cost of simplify branch)
lookup hit 80.7 ns/op 72.7 ns/op -9.9% faster
lookup miss 45.9 ns/op 36.6 ns/op -20.3% faster

The hot path (lookups) now beats master by 10-20%.

In find(), when a static child lookup misses, the code previously did a
linear scan of ALL children to find a {{param}} child. This is O(n) per
tree level for every parameterized route lookup.

Fix: Cache param_child_ pointer during find_or_create(), so find() can
fall back to it in O(1) instead of scanning.

Benchmark results (median, 25 iterations, WSL2 g++ -O2):

                 Before        After         Change
  insert:        313.3 ns/op   299.2 ns/op   -4.5%
  lookup hit:     80.7 ns/op    72.7 ns/op   -9.9%
  lookup miss:    45.0 ns/op    36.6 ns/op  -18.7%
@cong1920

Copy link
Copy Markdown
Owner Author

Committed directly to simplify_drt_node instead.

@cong1920 cong1920 closed this Mar 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant